package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.enums.ReachTypeEnum;
import com.xmy.cultivate.enums.StatusRecordEnum;
import com.xmy.cultivate.feign.english.IFeiEnglishFeignClient;
import com.xmy.cultivate.mapper.ServiceFeedbackMapper;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 服务反馈 服务实现类
 * </p>
 *
 * @author hpiggy
 * @since 2023-10-28
 */
@Service
public class ServiceFeedbackServiceImpl extends ServiceImpl<ServiceFeedbackMapper, ServiceFeedback> implements IServiceFeedbackService {

    @Autowired
    @Lazy
    ServiceFeedbackMapper serviceFeedbackMapper;

    @Autowired
    @Lazy
    IServiceDetectionService iServiceDetectionService;

    @Autowired
    @Lazy
    IServicePuchCardService iServicePuchCardService;

    @Autowired
    @Lazy
    IStudentLessonNumService iStudentLessonNumService;

    @Autowired
    @Lazy
    IRecordCourseService iRecordCourseService;

    @Autowired
    @Lazy
    IFeiEnglishFeignClient iFeiEnglishFeignClient;

    @Autowired
    @Lazy
    ILackCourseLogService iLackCourseLogService;

    @Override
    public IPage<ServiceFeedback> getFeedBadckList(IPage<?> page, Integer yearPart, Integer quarterNum, Long schoolId, Integer yearClassId, Long teacherId, Long gradeId,Long subjectsId, Integer lessonNum, String studentName,String idStrs){
        IPage<ServiceFeedback> iPage = serviceFeedbackMapper.getFeedBadckList(page,yearPart,quarterNum,schoolId,yearClassId,teacherId,gradeId ,subjectsId,lessonNum,studentName,idStrs);
        for (ServiceFeedback serviceFeedback:iPage.getRecords()){
            if (serviceFeedback.getLessonNum() == null){
                //System.out.println("为null:"+serviceFeedback.getId());
                continue;
            }
            Long feedbackId = serviceFeedback.getFeedbackId()!= null ? serviceFeedback.getFeedbackId():0;
            List<ServiceDetection> serviceDetectionList = serviceFeedbackMapper.getDetectiontListForFeedBackId(feedbackId);
            List<ServicePuchCard> servicePuchCardList = serviceFeedbackMapper.getPuchCardListForFeedBackId(feedbackId);
            serviceFeedback.setDetectionList(serviceDetectionList);
            serviceFeedback.setPuchCardList(servicePuchCardList);

            RecordCourse recordCourse = iRecordCourseService.getStudentClassStatus(serviceFeedback.getYearPart(),serviceFeedback.getQuarterNum(),serviceFeedback.getStudentId(),serviceFeedback.getSubjectsId(),serviceFeedback.getLessonNum());
            if (recordCourse != null){
                /**
                 * 精品课出勤情况:
                 * 1:准时
                 * 2:迟到
                 * 3:请假
                 * 4:缺课
                 * 5:调课
                 * 6:请假 (已补课)
                 * 7缺课 (已补课)
                 */

                //课程类别：1精品课（正常排课），4调课，6缺课补课
                if (recordCourse.getCourseType() != null && recordCourse.getCourseType().equals(1)){
                    if (recordCourse.getStatus().equals(StatusRecordEnum.REACH) && recordCourse.getReachType().equals(ReachTypeEnum.NORMAL)){
                        serviceFeedback.setSignIn01(1);
                    }else if (recordCourse.getStatus().equals(StatusRecordEnum.REACH) && recordCourse.getReachType().equals(ReachTypeEnum.LATE)){
                        serviceFeedback.setSignIn01(2);
                    }else if (recordCourse.getStatus().equals(StatusRecordEnum.LEAVE) && !recordCourse.getIsRepair().equals(1)){
                        serviceFeedback.setSignIn01(3);
                    }else if (recordCourse.getStatus().equals(StatusRecordEnum.LEAVE) && recordCourse.getIsRepair().equals(1)){
                        serviceFeedback.setSignIn01(6);
                    }
                }else if (recordCourse.getCourseType() != null && recordCourse.getCourseType().equals(4)){
                    serviceFeedback.setSignIn01(5);
                }else if (recordCourse.getCourseType() != null && recordCourse.getCourseType().equals(6)){
                    serviceFeedback.setSignIn01(7);
                }
            }else {
                LackCourseLog lackCourseLog = iLackCourseLogService.getLackCoruseLogForStudent(serviceFeedback.getYearPart(),serviceFeedback.getQuarterNum(),serviceFeedback.getStudentId(),serviceFeedback.getSubjectsId(),serviceFeedback.getLessonNum());
                if (lackCourseLog !=null){
                    serviceFeedback.setSignIn01(4);
                }
            }


            Map<String,Object> paramMap = new HashMap<>();
            paramMap.put("yearPart",serviceFeedback.getYearPart());
            paramMap.put("quarterNum",serviceFeedback.getQuarterNum());
            paramMap.put("studentId",serviceFeedback.getStudentId());
            paramMap.put("yearClassId",serviceFeedback.getYearClassId());
            paramMap.put("lessonNum",serviceFeedback.getLessonNum());
            try {
                Map<String,Object> rsMap = iFeiEnglishFeignClient.getPassNumForLessonNum(paramMap);
                if (rsMap != null){
                    rsMap.get("lowestShutNum");
                    String lowestShutNum = rsMap.get("lowestShutNum") == null ? "0" : rsMap.get("lowestShutNum").toString();
                    String maxPassShutNum = rsMap.get("maxPassShutNum") == null ? "0" : rsMap.get("maxPassShutNum").toString();
                    serviceFeedback.setPassNum01(Integer.parseInt(maxPassShutNum));
                    serviceFeedback.setShowPassNum01(Integer.parseInt(lowestShutNum));
                }
            }catch (Exception e){

            }
        }
        return iPage;
    }

    public ServiceFeedback getFeedBackOne(Long id){
        ServiceFeedback serviceFeedback = serviceFeedbackMapper.getFeedBackOne(id);
        if (serviceFeedback!=null){
            Long feedbackId = serviceFeedback.getFeedbackId()!= null ? serviceFeedback.getFeedbackId():0;
            List<ServiceDetection> serviceDetectionList = serviceFeedbackMapper.getDetectiontListForFeedBackId(feedbackId);
            List<ServicePuchCard> servicePuchCardList = serviceFeedbackMapper.getPuchCardListForFeedBackId(feedbackId);
            serviceFeedback.setDetectionList(serviceDetectionList);
            serviceFeedback.setPuchCardList(servicePuchCardList);

            Map<String,Object> paramMap = new HashMap<>();
            paramMap.put("yearPart",serviceFeedback.getYearPart());
            paramMap.put("quarterNum",serviceFeedback.getQuarterNum());
            paramMap.put("studentId",serviceFeedback.getStudentId());
            paramMap.put("yearClassId",serviceFeedback.getYearClassId());
            paramMap.put("lessonNum",serviceFeedback.getLessonNum());
            Map<String,Object> rsMap = iFeiEnglishFeignClient.getPassNumForLessonNum(paramMap);
            if (rsMap != null){
                rsMap.get("lowestShutNum");
                String lowestShutNum = rsMap.get("lowestShutNum") == null ? "0" : rsMap.get("lowestShutNum").toString();
                String maxPassShutNum = rsMap.get("maxPassShutNum") == null ? "0" : rsMap.get("maxPassShutNum").toString();
                serviceFeedback.setPassNum01(Integer.parseInt(maxPassShutNum));
                serviceFeedback.setShowPassNum01(Integer.parseInt(lowestShutNum));
            }
        }
        return serviceFeedback;
    }

    @Transactional
    public Result updateOne(ServiceFeedback serviceFeedback){

        Long lessonNumId = serviceFeedback.getId();
        StudentLessonNum studentLessonNum = null;
        if (lessonNumId == null){
            QueryWrapper<StudentLessonNum> studentLessonNumQueryWrapper = new QueryWrapper<>();
            studentLessonNumQueryWrapper.eq("student_id",serviceFeedback.getStudentId());
            studentLessonNumQueryWrapper.eq("subjects_id",serviceFeedback.getSubjectsId());
            studentLessonNumQueryWrapper.eq("year_part",serviceFeedback.getYearPart());
            studentLessonNumQueryWrapper.eq("quarter_num",serviceFeedback.getQuarterNum());
            studentLessonNumQueryWrapper.eq("lesson_num",serviceFeedback.getLessonNum());
            studentLessonNumQueryWrapper.last("limit 1");

            studentLessonNum = iStudentLessonNumService.getOne(studentLessonNumQueryWrapper);
            if (studentLessonNum == null){
                return new Result(Code.ERROR,"","课次不存在");
            }
            lessonNumId = studentLessonNum.getId();
        }else {
            studentLessonNum = iStudentLessonNumService.getById(lessonNumId);
            if (studentLessonNum == null){
                return new Result(Code.ERROR,"","课次不存在");
            }
        }


        QueryWrapper<ServiceFeedback> serviceFeedbackQueryWrapper = new QueryWrapper<>();
        serviceFeedbackQueryWrapper.eq("lesson_num_id",lessonNumId);
        ServiceFeedback serviceFeedbackOld = serviceFeedbackMapper.selectOne(serviceFeedbackQueryWrapper);
        if (serviceFeedbackOld!=null){
            serviceFeedback.setId(serviceFeedbackOld.getId());
        }

        serviceFeedback.setLessonNumId(lessonNumId);
        serviceFeedback.setYearPart(studentLessonNum.getYearPart());
        serviceFeedback.setQuarterNum(studentLessonNum.getQuarterNum());
        serviceFeedback.setLessonNum(studentLessonNum.getLessonNum());

        this.saveOrUpdate(serviceFeedback);

        Long feedBackId = serviceFeedback.getId();
        iServiceDetectionService.remove(new QueryWrapper<ServiceDetection>().eq("feedback_id",feedBackId));
        iServicePuchCardService.remove(new QueryWrapper<ServicePuchCard>().eq("feedback_id",feedBackId));

        if (serviceFeedback.getSubjectsId().equals(1L)){
            for (ServiceDetection serviceDetection:serviceFeedback.getDetectionList()){
                serviceDetection.setFeedbackId(feedBackId);
                iServiceDetectionService.save(serviceDetection);
            }
        }
        for (ServicePuchCard servicePuchCard:serviceFeedback.getPuchCardList()){
            servicePuchCard.setFeedbackId(feedBackId);
            iServicePuchCardService.save(servicePuchCard);
        }
        return new Result(Code.OK,"","成功");
    }

    @Override
    public List<ServiceFeedback> getFeedBadckAttendanceList(String studentId, String yearPart, String quarterNum, String subjectsId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", studentId);
        queryWrapper.eq("subjects_id", subjectsId);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum),"quarter_num",quarterNum);
        queryWrapper.eq(StringUtils.isNotBlank(yearPart),"year_part",yearPart);
        List<ServiceFeedback> list = list(queryWrapper);
        for (ServiceFeedback serviceFeedback: list) {
            if (serviceFeedback.getLessonNum() == null){
                //System.out.println("为null:"+serviceFeedback.getId());
                continue;
            }

            RecordCourse recordCourse = iRecordCourseService.getStudentClassStatus(serviceFeedback.getYearPart(),serviceFeedback.getQuarterNum(),serviceFeedback.getStudentId(),serviceFeedback.getSubjectsId(),serviceFeedback.getLessonNum());
            if (recordCourse != null){
                /**
                 * 精品课出勤情况:
                 * 1:准时
                 * 2:迟到
                 * 3:请假
                 * 4:缺课
                 * 5:调课
                 * 6:请假 (已补课)
                 * 7缺课 (已补课)
                 */

                //课程类别：1精品课（正常排课），4调课，6缺课补课
                if (recordCourse.getCourseType() != null && recordCourse.getCourseType().equals(1)){
                    if (recordCourse.getStatus().equals(StatusRecordEnum.REACH) && recordCourse.getReachType().equals(ReachTypeEnum.NORMAL)){
                        serviceFeedback.setSignIn01(1);
                    }else if (recordCourse.getStatus().equals(StatusRecordEnum.REACH) && recordCourse.getReachType().equals(ReachTypeEnum.LATE)){
                        serviceFeedback.setSignIn01(2);
                    }else if (recordCourse.getStatus().equals(StatusRecordEnum.LEAVE) && !recordCourse.getIsRepair().equals(1)){
                        serviceFeedback.setSignIn01(3);
                    }else if (recordCourse.getStatus().equals(StatusRecordEnum.LEAVE) && recordCourse.getIsRepair().equals(1)){
                        serviceFeedback.setSignIn01(6);
                    }
                }else if (recordCourse.getCourseType() != null && recordCourse.getCourseType().equals(4)){
                    serviceFeedback.setSignIn01(5);
                }else if (recordCourse.getCourseType() != null && recordCourse.getCourseType().equals(6)){
                    serviceFeedback.setSignIn01(7);
                }
            }else {
                LackCourseLog lackCourseLog = iLackCourseLogService.getLackCoruseLogForStudent(serviceFeedback.getYearPart(),serviceFeedback.getQuarterNum(),serviceFeedback.getStudentId(),serviceFeedback.getSubjectsId(),serviceFeedback.getLessonNum());
                if (lackCourseLog !=null){
                    serviceFeedback.setSignIn01(4);
                }
            }

            //circumference 每周打卡次数
            QueryWrapper queryWrapperServicePuchCard = new QueryWrapper<>();
            queryWrapperServicePuchCard.eq("feedback_id", serviceFeedback.getId());
            queryWrapperServicePuchCard.eq("status", 1);
            long count = iServicePuchCardService.count(queryWrapperServicePuchCard);
            serviceFeedback.setCircumference((int) count);

            //科目 为 英语 时
            if (Objects.equals(subjectsId, "1")) {
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("yearPart", serviceFeedback.getYearPart());
                paramMap.put("quarterNum", serviceFeedback.getQuarterNum());
                paramMap.put("studentId", serviceFeedback.getStudentId());
                paramMap.put("yearClassId", serviceFeedback.getYearClassId());
                paramMap.put("lessonNum", serviceFeedback.getLessonNum());
                try {
                    Map<String, Object> rsMap = iFeiEnglishFeignClient.getPassNumForLessonNum(paramMap);
                    if (rsMap != null) {
                        rsMap.get("lowestShutNum");
                        String lowestShutNum = rsMap.get("lowestShutNum") == null ? "0" : rsMap.get("lowestShutNum").toString();
                        String maxPassShutNum = rsMap.get("maxPassShutNum") == null ? "0" : rsMap.get("maxPassShutNum").toString();
                        serviceFeedback.setPassNum01(Integer.parseInt(maxPassShutNum));
                        serviceFeedback.setShowPassNum01(Integer.parseInt(lowestShutNum));
                    }
                } catch (Exception e) {

                }
            }
        }
        return list;
    }
}
